package com.bawei.mall.search.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.mall.product.domain.MallProductInfo;
import com.bawei.mall.product.domain.reponse.ProductInfoResponse;
import com.bawei.mall.product.remote.RemoteProductInfo;
import com.bawei.mall.search.domain.request.SearchReq;
import com.bawei.mall.search.es.instance.EsInstance;
import com.bawei.mall.search.es.service.EsDataService;
import com.bawei.mall.search.service.SearchService;
import com.bawei.mall.search.utils.SearchResultUtils;
import com.bawei.system.remote.api.RemoteEsDocService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
//import org.apache.lucene.search.TotalHits;
//import org.elasticsearch.action.search.SearchRequest;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.client.RequestOptions;
//import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.common.text.Text;
//import org.elasticsearch.index.query.BoolQueryBuilder;
//import org.elasticsearch.index.query.MatchQueryBuilder;
//import org.elasticsearch.index.query.QueryBuilders;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.SearchHits;
//import org.elasticsearch.search.builder.SearchSourceBuilder;
//import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
//import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author DongZl
 * @description: 搜索业务实现类
 * @Date 2022-10-21 下午 02:53
 */
@Service
public class SearchServiceImpl implements SearchService {

    private static final Logger log = LoggerFactory.getLogger(SearchServiceImpl.class);

//    @Autowired
//    private RemoteProductInfo remoteProductInfo;

    @Autowired
    private EsDataService esDataService;

    @Autowired
    private RemoteEsDocService remoteEsDocService;

    @Autowired
    private EsInstance esInstance;

//    @Autowired
//    private RestHighLevelClient restHighLevelClient;

    private static final String INDEX_NAME="product_info";

    @Override
    public void syncProductInfo (Long productId) {
//        R<ProductInfoResponse> resultInfo = remoteProductInfo.getResultInfo(productId);
//        esDataService.insertOrUpdate("shop_item", resultInfo.getData());
//        log.info("商品:[{}]同步完成", productId);
    }

    /**
     * 搜索
     *
     * @param searchReq
     */
    @Override
    public R<MallProductInfo> search (SearchReq searchReq) {
//        long total = 0;
//        ArrayList<MallProductInfo> productInfos = new ArrayList<>();
//        try {
//            if (StringUtils.isEmpty(searchReq.getKeyWord())){
//                throw new ServiceException("搜索参数不可以为空");
//            }
//
//            SearchRequest searchRequest = esInstance.SearchRequestBuilder(INDEX_NAME);
//            SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
//            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//            // 商品名称搜索
//            boolQueryBuilder.must(QueryBuilders.matchQuery("name",searchReq.getKeyWord()));
//            searchSourceBuilder.query(boolQueryBuilder);
//            // 分页
//            searchSourceBuilder.from((searchReq.getPageNum() - 1) * searchReq.getPageSize());
//            searchSourceBuilder.size(searchReq.getPageSize());
//
//            searchSourceBuilder.highlighter(
//                    new HighlightBuilder()
//                            .field("name")
//                            .preTags("<span style=\"color:red\">")
//                            .postTags("</span>"));
//            searchRequest.source(searchSourceBuilder);
//
//            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//            SearchHits searchHits = searchResponse.getHits();
//            total=searchHits.getTotalHits().value;
//            for (SearchHit searchHit : searchHits) {
//                String sourceAsString = searchHit.getSourceAsString();
//                MallProductInfo mallProductInfo = JSONObject.parseObject(sourceAsString, MallProductInfo.class);
//                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
//                if(highlightFields!=null){
//                    HighlightField highlightField = highlightFields.get("name");
//                    if(highlightField!=null){
//                        Text[] fragments = highlightField.getFragments();
//                        StringBuilder sb = new StringBuilder();
//                        for (Text fragment : fragments) {
//                            sb.append(fragment);
//                        }
//                        mallProductInfo.setName(sb.toString());
//                    }
//                }
//                productInfos.add(mallProductInfo);
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//
//        return PageResult.toPageResult(total,productInfos);
        return null;
    }

    @Override
    public R querySuggestions(String indexName, String keyWord, String suggestFiled) {
        R r = remoteEsDocService.querySuggestions(indexName, keyWord, suggestFiled);
        return r;
    }
}
